const express = require("express");
const sql = require("mssql");
const cors = require("cors");

const app = express();
const port = process.env.PORT || 3000;

// 支持跨域
app.use(cors());

// SQL Server 配置
const config = {
  user: process.env.DB_USER || "skevisit",
  password: process.env.DB_PASS || "skevisit_2017",
  server: process.env.DB_HOST || "10.2.91.221",
  port: parseInt(process.env.DB_PORT, 10) || 1433,
  database: process.env.DB_NAME || "skedb2020",
  options: {
    encrypt: false,
    trustServerCertificate: true,
  },
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000,
  },
};

// 创建连接池
const pool = new sql.ConnectionPool(config);
const poolConnect = pool.connect();

// 分页查询 Visit_View（兼容旧版 SQL Server）
app.get("/api/visit", async (req, res) => {
  const page = parseInt(req.query.page, 10) || 1;
  const pageSize = parseInt(req.query.pageSize, 10) || 20;
  const offset = (page - 1) * pageSize;

  try {
    await poolConnect;
    // 获取总数
    const countResult = await pool
      .request()
      .query("SELECT COUNT(*) as total FROM Visit_View");
    const total = countResult.recordset[0].total;

    // 兼容旧版 SQL Server 的分页查询
    const sqlText = `
      SELECT * FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY [序号]) AS RowNum, * FROM Visit_View
      ) AS T
      WHERE T.RowNum BETWEEN ${offset + 1} AND ${offset + pageSize}
    `;
    const result = await pool.request().query(sqlText);
    res.json({
      data: result.recordset,
      total,
      page,
      pageSize,
    });
  } catch (err) {
    console.error("查询 Visit_View 出错:", err);
    res.status(500).send("服务器错误");
  }
});

// 查询 ShiC_View（只返回前10条数据，不分页）
app.get("/api/shic", async (req, res) => {
  try {
    await poolConnect;
    const result = await pool.request().query("SELECT TOP 10 * FROM ShiC_View");
    res.json({
      data: result.recordset,
    });
  } catch (err) {
    console.error("查询 ShiC_View 出错:", err);
    res.status(500).send("服务器错误");
  }
});

app.use((req, res) => {
  res.status(404).send("接口不存在");
});

app.listen(port, () => {
  console.log(`API 服务已启动，端口: ${port}`);
});
